package cn.py.boot_lua.controller.test;

import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class VideoFirstFrameExtractor {

    public static void main(String[] args) {
        String videoFilePath = "C:/Users/Administrator/Desktop/video/a21593f817.mp4";
        String outputImagePath = "D:\\javaXM\\boot_lua\\src\\main\\resources\\static\\first_frame.jpg"; // 输出图片路径
        extractFirstFrame(videoFilePath, outputImagePath);
    }

    public static void extractFirstFrame(String videoPath, String outputPath) {
        // 设置 Ffmpeg 静默模式，关闭日志输出
        avutil.av_log_set_level(avutil.AV_LOG_QUIET);
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath);
        Java2DFrameConverter converter = new Java2DFrameConverter();
        try {
            grabber.start();
            Frame frame;
            int frameNumber = 0;
            // 循环读取帧直到获取到第一个非空帧
            while ((frame = grabber.grab()) != null) {
                if (frameNumber == 0 && frame.image != null) {
                    BufferedImage bufferedImage = converter.getBufferedImage(frame);
                    ImageIO.write(bufferedImage, "jpg", new File(outputPath));
                    System.out.println("成功保存第一帧至: " + outputPath);
                    break;
                }
                frameNumber++;
            }

        } catch (Exception e) {
            System.err.println("提取第一帧时发生错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                grabber.stop(); // 停止抓取
                grabber.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

